package com.yunshipei.ui.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;

import com.google.zxing.activity.CaptureActivity;
import com.yunshipei.base.BaseActivity;
import com.yunshipei.base.BaseIntentBuilder;
import com.yunshipei.common.ExitApps;
import com.yunshipei.common.Globals;
import com.yunshipei.common.LoginManager;
import com.yunshipei.common.SendManager;
import com.yunshipei.common.UserLoginDataParser;
import com.yunshipei.common.exception.UserAuthException;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.common.XCloudException;
import com.yunshipei.core.manager.TabManager;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.core.model.WaterMarkConfig;
import com.yunshipei.core.ui.TabFragment;
import com.yunshipei.core.utils.CommonUtils;
import com.yunshipei.core.utils.NetUtils;
import com.yunshipei.core.utils.SystemUtils;
import com.yunshipei.core.utils.YspLogUtils;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.UpdateManager;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.AppConfigModel;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.PointModel;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.WaterMarkSettings;
import com.yunshipei.model.YspEvent;
import com.yunshipei.model.YspEvent.ClearDevicesEvent;
import com.yunshipei.model.YspEvent.MessageNumEvent;
import com.yunshipei.model.YspEvent.StartBrowserEvent;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.ui.fragment.BaseNavFragment;
import com.yunshipei.ui.fragment.BrowserFragment;
import com.yunshipei.ui.fragment.CollectionFragment;
import com.yunshipei.ui.fragment.HomeFragment;
import com.yunshipei.ui.fragment.LabelFragment;
import com.yunshipei.ui.fragment.NavigationFragment;
import com.yunshipei.ui.fragment.NoContactsNavigationFragment;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.EncUtils;
import com.yunshipei.utils.FileUtils;
import com.yunshipei.utils.LogHandlerUtils;
import com.yunshipei.utils.ToastUtils;
import com.yunshipei.utils.YspProtocolUtils;

import org.json.JSONObject;
import org.reactivestreams.Publisher;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

import static com.google.zxing.activity.CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN;


@SuppressLint({"RtlHardcoded", "CommitPrefEdits"})
public class MainActivity extends BaseActivity implements HomeFragment.OnFragmentInteractionListener, NavigationFragment.NavigationInteractionListener, CollectionFragment.CollectionShowInteractionListener, LabelFragment.OnLabelInteractionListener, BrowserFragment.BrowserInteractionListener {

    private static final int REQUEST_CODE = 523;

    private static final String PREFERENCES_CLEAR_DEVICES1 = "clear_devices_data1";
    private static final String EXTRA_NEW_WEB_APP_URL = "extra_new_web_app_url";

    private static final String ACTION_DEVICES_OFFLINE_EVENT = "action_devices_offline_event";
    private static final String ACTION_OPEN_NEW_WEB_APP = "action_open_new_web_app";

    public static final String ACTION_QR_CODE_DATA_RESULT = "action_ar_code_action";
    public static final String ACTION_DMEO_AGREE_REQUEST = "action_demo_agree_request";
    public static final String ACTION_DMEO_GROUP_MESSAGE = "action_demo_group_message";
    public static final String EXTRA_MAIN_DATA = "com.enterplorer.main_data";
    public static final String EXTRA_AUTO_LOGIN = "com.enterplorer.auto_login";
    public static final String EXTRA_QR_CODE_CONTENT_IS_ADAPTER = "com.enterplorer.qr_content_adapter";

    @Bind(R.id.main_drawer_layout)
    protected DrawerLayout mDrawerLayout;

    private MainExtraBean mMainExtraBean;
    private boolean isAutoLogin = false;
    private boolean hasConfig = false;
    private boolean reStartFromMemory = false;

    private SharedPreferences mPreferences;
    private SharedPreferences mNoClearPreferences;
    //左抽屉
    private LabelFragment mLabelFragment;
    //浏览器与主页
    private BrowserFragment mBrowserFragment;
    private BaseNavFragment mBaseNavFragment;

    private static boolean isActivityRecreated = false;  //当主题色变化时，activity重建，不需要自动登录

    public static final Conversation.ConversationType[] CONVERSATION_TYPES = {Conversation.ConversationType.PRIVATE, Conversation.ConversationType.GROUP};

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);
        this.mPreferences = YspPreferences.getInstance().getSharedPreferences();
        this.mNoClearPreferences = getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE);
        Intent intent = getIntent();
        this.mMainExtraBean = (MainExtraBean) intent.getSerializableExtra(EXTRA_MAIN_DATA);
        this.isAutoLogin = intent.getBooleanExtra(EXTRA_AUTO_LOGIN, false);

        Log.e("isAutoLogin",isAutoLogin+"");
        if (savedInstanceState == null) {
            if (isAutoLogin) {
                mBaseNavFragment = mMainExtraBean.isUseContacts() ? NavigationFragment.newInstances(mMainExtraBean, true) : NoContactsNavigationFragment.newInstance(mMainExtraBean, true);
                getSupportFragmentManager().beginTransaction().replace(R.id.fl_main_content, mBaseNavFragment, BaseNavFragment.class.getName()).commit();
            } else {
                mLabelFragment = LabelFragment.newInstances(mMainExtraBean);
                mBaseNavFragment =  NavigationFragment.newInstances(mMainExtraBean);
                mBrowserFragment = BrowserFragment.newInstances(mMainExtraBean);
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.fl_main_content, mBrowserFragment, BrowserFragment.class.getName()).add(R.id.fl_main_content, mBaseNavFragment, BaseNavFragment.class.getName())
                        .replace(R.id.main_left_collection_container, mLabelFragment, LabelFragment.class.getName()).commit();
                boolean currentUseContacts = mMainExtraBean.isUseContacts();
                //上次是否使用通讯录，保存的状态，状态为0默认值，说明本地没有存取上次状态，不提示。1-->上次使用通讯录，2-->上次不使用通讯录
                int contactsStatus = mNoClearPreferences.getInt(Globals.YSP_NO_CLEAR_CONTACTS_MODEL, 0);
                if (contactsStatus == 1 && !currentUseContacts) {
                    showSwitchIMMsg(false);
                } else if (contactsStatus == 2 && currentUseContacts) {
                    showSwitchIMMsg(true);
                }
            }
        } else {
            //华为手机内存启动时，getIntent获取不到extra对象
            if (mMainExtraBean == null) {
                // 这种情况目前仅在华为手机上(mate8,其他的应该也有)出现过，当activity被系统回收，再次启动app时，
                // 也就是savedInstanceState != null 的时候，从intent中获取data是获取不到的，onSavedInstancesState也不执行，所以在此进入启动也加载缓存，保证不会crash
                final String cacheLoginData = EncUtils.decrypt(mPreferences.getString(Globals.UUID, ""), mPreferences.getString(Globals.SP_LOGIN_DATA, ""));
                this.mMainExtraBean = new UserLoginDataParser(this).parse(cacheLoginData);
            }
            isAutoLogin = !isActivityRecreated;
            reStartFromMemory = true;
            mLabelFragment = (LabelFragment) getSupportFragmentManager().findFragmentByTag(LabelFragment.class.getName());
            mBaseNavFragment = (BaseNavFragment) getSupportFragmentManager().findFragmentByTag(BaseNavFragment.class.getName());
            mBrowserFragment = (BrowserFragment) getSupportFragmentManager().findFragmentByTag(BrowserFragment.class.getName());
            if (!mBrowserFragment.isHidden()) {
                getSupportFragmentManager().beginTransaction().hide(mBrowserFragment).commit();
            }
            if (mBaseNavFragment.isHidden()) {
                getSupportFragmentManager().beginTransaction().show(mBaseNavFragment).commit();
            }
        }
        mDrawerLayout.addDrawerListener(mDrawerListener);
    }

    private boolean open = false;

    private DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.SimpleDrawerListener() {
        @Override
        public void onDrawerOpened(View drawerView) {
            mBrowserFragment.hideExtraMenu();
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            if (!open) {
                open = true;
                refreshDrawerContent();
            }
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            super.onDrawerStateChanged(newState);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            open = false;
            EventBus.getDefault().post(new YspEvent.UpdateTabCount());
        }
    };

    private void refreshDrawerContent() {
        if (mBaseNavFragment.isHidden()) {
            TabFragment tabFragment = mBrowserFragment.getCurrentFragment();
            if (tabFragment != null) {
                int pos = TabManager.getInstance().getTabPosition(tabFragment.getStartURL());
                mLabelFragment.onRefresh(pos + 1);
            }
        } else {
            mLabelFragment.onRefresh(0);
        }
    }

    //========================初始化数据与登录接口数据=========================
    //从网络加载最新数据，走的登录接口
    //如果接口数据加载成功之后，或者使用缓存才初始化适配相关数据
    private void loadDataFromNet() {
        showLoadingMsg(getString(R.string.load_data_from_net));
        boolean netOk = NetUtils.isNetworkAvailable(this);
        Flowable.just(netOk).flatMap(new Function<Boolean, Publisher<MainExtraBean>>() {
            @Override
            public Publisher<MainExtraBean> apply(Boolean aBoolean) throws Exception {
                LoginManager loginManager = new LoginManager(MainActivity.this);
                if (aBoolean) {
                    return loginManager.autoLogin();
                }
                return Flowable.error(new XCloudException(getString(R.string.net_no_connect)));
            }
        }).doOnError(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                if (!(throwable instanceof UserAuthException)) {
                    initAdapterPkgManifest();
                }
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MainExtraBean>() {
            @Override
            public void accept(MainExtraBean mainExtraBean) throws Exception {
                MainExtraBean temp = mMainExtraBean;
                boolean lastUseContacts = temp.isUseContacts();
                boolean currentUseContacts = mainExtraBean.isUseContacts();
                if (lastUseContacts == !currentUseContacts) {
                    showSwitchIMMsg(currentUseContacts);
                }
                mMainExtraBean = mainExtraBean;
                getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE).edit().putString(Globals.SP_COMPANY_THEME_CODE, mainExtraBean.getThemeCode()).apply();
                mLabelFragment = LabelFragment.newInstances(mMainExtraBean);
                mBaseNavFragment = mMainExtraBean.isUseContacts() ? NavigationFragment.newInstances(mMainExtraBean) : NoContactsNavigationFragment.newInstance(mMainExtraBean);
                mBrowserFragment = BrowserFragment.newInstances(mMainExtraBean);
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fl_main_content, mBrowserFragment, BrowserFragment.class.getName())
                        .add(R.id.fl_main_content, mBaseNavFragment, BaseNavFragment.class.getName())
                        .replace(R.id.main_left_collection_container, mLabelFragment, LabelFragment.class.getName()).commit();
                if (reStartFromMemory && !mBrowserFragment.isHidden()) {
                    getSupportFragmentManager().beginTransaction().hide(mBrowserFragment).commit();
                }
                setIntent(new Intent().putExtra(EXTRA_MAIN_DATA, mainExtraBean));
                String companyName = mNoClearPreferences.getString(Globals.SP_COMPANY_HOST, "");
                new SendManager().sendAdapterLog(companyName, mMainExtraBean.getUserInfo().getTel());
                dismissLoadingDialog();

                //判断主题是否修改,如果主题修改了，则重新创建activity
                String themeCode = mMainExtraBean.getThemeCode();
                String lastThemeCode = EnterConfig.getInstance().getThemeCode();
                if (!TextUtils.isEmpty(themeCode) && !themeCode.equals(lastThemeCode)) {
                    EnterConfig.getInstance().setThemeCode(themeCode);
                    isActivityRecreated = true;
                    recreate();
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                if (throwable instanceof UserAuthException) {
                    dismissLoadingDialog();
                    ToastUtils.showToast(throwable.getMessage());
                    startActivity(new Intent(MainActivity.this, SystemUtils.isPad(MainActivity.this) ? LoginActivity.class : H5LoginActivity.class));
                    finish();
                } else {
                    if (!reStartFromMemory) {
                        mBaseNavFragment.resetIM();
                        mLabelFragment = LabelFragment.newInstances(mMainExtraBean);
                        mBrowserFragment = BrowserFragment.newInstances(mMainExtraBean);
                        getSupportFragmentManager().beginTransaction()
                                .add(R.id.main_left_collection_container, mLabelFragment, LabelFragment.class.getName())
                                .add(R.id.fl_main_content, mBrowserFragment, BrowserFragment.class.getName())
                                .commit();
                        getSupportFragmentManager().beginTransaction().hide(mBrowserFragment).commit();  //三星4.4.2的系统这里必须单独获取一个FragmentManager来隐藏它，不然不会crash，不知道4.4是不是普遍需要这样做
                        setIntent(new Intent().putExtra(EXTRA_MAIN_DATA, mMainExtraBean));
                    }
                    dismissLoadingDialog();
                    ToastUtils.showToast(XCloudSDKManager.getInstance().generateError(throwable));
                }
            }
        });
    }

    //因为适配SDK中部分数据采用单例的形式传递，如果登录没有成功，仍然需要初始化这一部分数据
    private void initAdapterPkgManifest() {
        Flowable.create(new FlowableOnSubscribe<JSONObject>() {
            @Override
            public void subscribe(FlowableEmitter<JSONObject> e) throws Exception {
                String cacheLoginData = "";
                String tempLoginCacheData = mPreferences.getString(Globals.SP_LOGIN_DATA, "");
                if (!TextUtils.isEmpty(tempLoginCacheData)) {
                    cacheLoginData = EncUtils.decrypt(mPreferences.getString(Globals.UUID, ""), tempLoginCacheData);
                }
                JSONObject jsonObject = new JSONObject(cacheLoginData);
                e.onNext(jsonObject);
            }
        }, BackpressureStrategy.BUFFER).flatMap(new Function<JSONObject, Publisher<JSONObject>>() {
            @Override
            public Publisher<JSONObject> apply(JSONObject jsonObject) throws Exception {
                String managerServer = mNoClearPreferences.getString(Globals.MANUAL_BASE_URL, "");
                if (TextUtils.isEmpty(managerServer)) {
                    managerServer = mNoClearPreferences.getString(Globals.SP_HUB_GET_SERVER, "");
                }
                return XCloudSDKManager.getInstance().prepareXCloudData(MainActivity.this, managerServer, jsonObject, true);
            }
        }).subscribe(new Consumer<JSONObject>() {
            @Override
            public void accept(JSONObject jsonObject) throws Exception {
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
            }
        });
    }

    //启用禁用IM弹窗提示
    private void showSwitchIMMsg(final boolean currentUseContacts) {
        String message = currentUseContacts ? getString(R.string.re_use_contacts) : getString(R.string.re_un_use_contacts);
        DialogHelper.showLicenseChangeAlert(this, message, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        mNoClearPreferences.edit().putInt(Globals.YSP_NO_CLEAR_CONTACTS_MODEL, currentUseContacts ? 1 : 2).apply();
    }

    //清除设备信息
    public void onEventMainThread(ClearDevicesEvent event) {
        SharedPreferences clearDevicesPreferences = this.getSharedPreferences(Globals.NO_CLEAR_SHP, Context.MODE_PRIVATE);
        String clearData = clearDevicesPreferences.getString(PREFERENCES_CLEAR_DEVICES1, "");
        if (!TextUtils.isEmpty(clearData)) {
            Object object = StringUtilSub.getEncodeBase64(clearData);
            if (object != null) {
                ClearDevicesEvent clearDevicesEvent = (ClearDevicesEvent) object;
                String devicesId = clearDevicesEvent.getDeviceId();
                if (!TextUtils.isEmpty(devicesId) && !devicesId.equals(event.getDeviceId()) || clearDevicesEvent.getGUID().equals(event.getGUID()))
                    return;
            }
        }
        clearDevicesPreferences.edit().putString(PREFERENCES_CLEAR_DEVICES1, StringUtilSub.base64(event)).apply();
        RongIMClient.getInstance().clearConversations(CONVERSATION_TYPES);
        new ExitApps(this).exitApps();
    }

    //进入浏览器事件
    public void onEventMainThread(StartBrowserEvent event) {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        //从其他页面进入浏览器，eg:消息推送,首页搜索，是从聊天界面过来，需要finish掉前面的所有Activity
        String url = event.getUrl();
        startActivity(new Intent(this, MainActivity.class).setAction(ACTION_OPEN_NEW_WEB_APP).putExtra(EXTRA_NEW_WEB_APP_URL, url));
    }

    private String mLastWebAppUrl = "";
    private String mDeveloperAdapterData = "";

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String action = intent.getAction();
        if (!TextUtils.isEmpty(action)) {
            switch (action) {
                case ACTION_DEVICES_OFFLINE_EVENT:
                    DialogHelper.showMultiDevicesError(this);
                    break;
                case ACTION_OPEN_NEW_WEB_APP:
                    mLastWebAppUrl = intent.getStringExtra(EXTRA_NEW_WEB_APP_URL);
                    break;
                case ACTION_QR_CODE_DATA_RESULT:
                    String result = intent.getStringExtra(INTENT_EXTRA_KEY_QR_SCAN);
                    if (!TextUtils.isEmpty(result)) {
                        boolean adapter = intent.getBooleanExtra(EXTRA_QR_CODE_CONTENT_IS_ADAPTER, false);
                        if (adapter) {
                            mDeveloperAdapterData = result;
                        } else {
                            mLastWebAppUrl = result;
                        }
                    }
                    break;
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!hasConfig) {
            hasConfig = true;
            initConfig();
        }
    }

    //配置客户端内容，目前水印在此配置
    private void initConfig() {
        final UserInfo userInfo = mMainExtraBean.getUserInfo();
        String companyID = userInfo.getCompanyId();
        HttpMethods.getInstance().getSetting(companyID).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<AppConfigModel.Data>() {
            @Override
            public void accept(AppConfigModel.Data data) throws Exception {
                AppConfigModel.Data.Watermark watermark = data.watermark;
                if (watermark != null && watermark.enableWatermark) {
                    WaterMarkConfig.Builder builder = new WaterMarkConfig.Builder();
                    builder.setShowDeviceID(watermark.showDeviceId);
                    builder.setShowDateTime(watermark.showTime);
                    builder.setWtmTextSize(BaseUtil.dip2px(MainActivity.this, watermark.watermarkFontSize));
                    String color = watermark.watermarkColor;
                    if (!TextUtils.isEmpty(color)) {
                        builder.setWtmColor(color);
                    }
                    builder.setWtmTransparency(watermark.watermarkOpacity);
                    ArrayList<String> wtms = new ArrayList<>();
                    if (watermark.showCustomer && !TextUtils.isEmpty(watermark.customerContent)) {
                        wtms.add(watermark.customerContent);
                    }
                    String userName = userInfo.getName();
                    if (watermark.showName && !TextUtils.isEmpty(userName)) {
                        wtms.add(userName);
                    }
                    String tel = userInfo.getTel();
                    if (watermark.showTel && !TextUtils.isEmpty(tel)) {
                        wtms.add(tel);
                    }
                    String email = userInfo.getEmail();
                    if (watermark.showEmail && !TextUtils.isEmpty(email)) {
                        wtms.add(email);
                    }
                    builder.setWtmTexts(wtms);
                    int type = Integer.parseInt(watermark.watermarkRange);
                    WaterMarkSettings waterMarkSettings = new WaterMarkSettings(type, builder.build());
                    EnterConfig.getInstance().setWaterMarkSettings(waterMarkSettings);
                    initWatermark();
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                YspLogUtils.d(throwable.toString());
            }
        });
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (isAutoLogin) {
            isAutoLogin = false;
            loadDataFromNet();
        } else if (!TextUtils.isEmpty(mLastWebAppUrl)) {
            openWebApp(mLastWebAppUrl);
            mLastWebAppUrl = "";
        } else if (!TextUtils.isEmpty(mDeveloperAdapterData)) {
            loadDeveloperAdapter(mDeveloperAdapterData);
            mDeveloperAdapterData = "";
        }
    }

    @Override
    public void openWebApp(String url) {
        //协议判断
        if (url.startsWith(Globals.NATIVE_EMAIL)) {
            statisticNativeApp(url);
            YspProtocolUtils.openEmailClient(this, "mailto:");
        } else if (url.startsWith(Globals.WARN_TO_DO)) {
            statisticNativeApp(url);
            YspProtocolUtils.launchWarnFunc(this);
        } else if (url.startsWith(Globals.BLUETOOTH)) {
            statisticNativeApp(url);
            YspProtocolUtils.launchSignIn(this);
        } else if (url.startsWith(Globals.NATIVE_OTHER_APP)) {
            statisticNativeApp(url);
            url = CommonUtils.removeParams(url, new String[]{Globals.WEB_APP_ID, Globals.WEB_APP_NAME, Globals.YSP_PARAM_FORCE_PC});
            String pack = url.substring(Globals.NATIVE_OTHER_APP.length(), url.endsWith("/") ? url.length() - 1 : url.length());
            YspProtocolUtils.launchNativeApp(this, pack);
        } else {
            Log.e("log",url);
            //此处不做统计，当把app的tab attach到页面会统计，包括tab的切换统计
            BaseUtil.modifyStatusBarColor(this, getResources().getColor(R.color.group_list_gray));
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();

            if (!mBaseNavFragment.isHidden()) {
                ft.hide(mBaseNavFragment);
            }
            if (mBrowserFragment.isHidden()) {
                ft.show(mBrowserFragment);
                ft.addToBackStack(null);
            }
            ft.commit();
            mBrowserFragment.handleApps(url);
        }
    }

    @Override
    public void openQRCode() {
        if (BaseUtil.isCameraAvailable()) {
            Intent intent = new Intent(this, CaptureActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        } else {
            ToastUtils.showToast(R.string.camera_permission_request);
        }
    }

    private void loadDeveloperAdapter(String result) {
        BaseUtil.modifyStatusBarColor(this, getResources().getColor(R.color.group_list_gray));
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (!mBaseNavFragment.isHidden()) {
            ft.hide(mBaseNavFragment);
        }
        if (mBrowserFragment.isHidden()) {
            ft.show(mBrowserFragment);
        }
        ft.commit();
        mBrowserFragment.addNewDeveloperTab(result);
    }

    private void statisticNativeApp(String url) {
        UserInfo userInfo = mMainExtraBean.getUserInfo();
        if (userInfo != null) {
            if (!TextUtils.isEmpty(url)) {
                String appID = "";
                String appName = "";
                Uri uri = Uri.parse(url);
                if (uri != null) {
                    appID = uri.getQueryParameter(Globals.WEB_APP_ID);
                    appName = uri.getQueryParameter(Globals.WEB_APP_NAME);
                }
                LogHandlerUtils.savePoint(new PointModel(url, userInfo, appID, appName));
            }
        }
    }

    @Override
    public void onDrawerOpen() {
        open = true;
        refreshDrawerContent();
        mDrawerLayout.openDrawer(Gravity.LEFT);
    }

    private WaitDialog mWaitDialog;

    private void showLoadingMsg(String message) {
        if (mWaitDialog == null) {
            mWaitDialog = new WaitDialog(this);
            mWaitDialog.setCancelable(false);
            mWaitDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    return keyCode == KeyEvent.KEYCODE_BACK;
                }
            });
        }
        mWaitDialog.setMessage(message);
        mWaitDialog.show();
    }

    private void dismissLoadingDialog() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
        }
    }
    //========================初始化登录数据成功=======================

    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
            mDrawerLayout.closeDrawers();
        } else {
            if (!mBaseNavFragment.isHidden()) {
                if (mBaseNavFragment instanceof NavigationFragment && ((NavigationFragment) mBaseNavFragment).canGoBack()) {
                    ((NavigationFragment) mBaseNavFragment).goBack();
                } else {
                    new SendManager().sendPoint();
                    moveTaskToBack(true);
                    processBackStack = true;
                }
            } else {
                mBrowserFragment.onBackPressed();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void closeAllTabs() {
        if (mBaseNavFragment.isHidden()) {
            getSupportFragmentManager().beginTransaction().hide(mBrowserFragment).show(mBaseNavFragment).commit();
        }
        TabManager.getInstance().removeAllViews();
        mDrawerLayout.closeDrawers();
    }

    @Override
    public void onTabHistoryItemClick(boolean isClose, int position) {
        if (mBaseNavFragment.isHidden()) {
            mBrowserFragment.onTabHistoryItemClick(isClose, position);
        } else {
            if (position == 0) {
                mDrawerLayout.closeDrawers();
                return;
            }
            if (isClose) {
                TabManager.getInstance().removeView(position - 1);
                //刷新tab中的集合
                mLabelFragment.onRefresh(0);
            } else {
                TabFragment tabFragment = TabManager.getInstance().getFragment(position - 1);
                if (tabFragment != null) {
                    String url = tabFragment.getStartURL();
                    if (!TextUtils.isEmpty(url)) {
                        openWebApp(url);
                    }
                }
                mDrawerLayout.closeDrawers();
            }
        }
    }

    @Override
    public String getHomeWebViewCaptureURL() {
        return mBaseNavFragment.captureHomeWebView();
    }

    @Override
    public void onCollectionItemClick(String url) {
        openWebApp(url);
        mDrawerLayout.closeDrawers();
    }

    @Override
    public void closeDrawers() {
        mDrawerLayout.closeDrawers();
    }

    @Override
    public void refreshTabDrawer(int position) {
        mLabelFragment.onRefresh(position);
    }

    @Override
    public void showNavigationFragment() {
        getSupportFragmentManager().beginTransaction().hide(mBrowserFragment).show(mBaseNavFragment).commit();
        BaseUtil.modifyStatusBarColor(this, EnterConfig.getInstance().getStatusBarGlobalColor());
        EventBus.getDefault().post(new YspEvent.UpdateTabCount());
    }

    @Override
    public DrawerLayout getDrawer() {
        return mDrawerLayout;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        resetSingleton();
    }

    private void resetSingleton() {
        EventBus.getDefault().unregister(this);
        TabManager.getInstance().destroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerHomeKeyReceiver(this);
        if (processBackStack) {
            processBackStack = false;
            //程序再次激活
            if (!NetUtils.isNetworkAvailable(this)) {
                ToastUtils.showToast(getString(R.string.net_no_connect));
                return;
            }
            new SendManager().sendPoint();
            UserInfo userInfo = mMainExtraBean.getUserInfo();
            if (userInfo == null) return;
            HttpMethods.getInstance().processRestart(userInfo.getCompanyId(), userInfo.getName(), userInfo.getUuid());
            if (mPreferences.getBoolean(Globals.SP_SPLASH_CHECK_UPDATE, true)) {
                new UpdateManager(this, false, true).checkUpdate(userInfo.getCompanyId());
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterHomeKeyReceiver(this);
    }

    //=============home键点击==============
    private boolean processBackStack = true;
    private BroadcastReceiver mHomeKeyReceiver = new BroadcastReceiver() {

        private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
        private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
                    processBackStack = true;
                    new SendManager().sendPoint();
                }
            }
        }
    };

    private void registerHomeKeyReceiver(Context context) {
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        context.registerReceiver(mHomeKeyReceiver, homeFilter);
    }

    private void unregisterHomeKeyReceiver(Context context) {
        context.unregisterReceiver(mHomeKeyReceiver);
    }
    //============home键点击结束=================

    public void onEventMainThread(final RongIMClient.ConnectionStatusListener.ConnectionStatus status) {
        if (status == RongIMClient.ConnectionStatusListener.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT) {
            mPreferences.edit().putBoolean(Globals.SP_MULTI_DEVICES, true).apply();
            startActivity(new Intent(this, MainActivity.class).setAction(ACTION_DEVICES_OFFLINE_EVENT));
        }
    }

    public void onEventMainThread(YspEvent.ConnectEvent event) {
        //设置未读消息数目监听
        RongIM.getInstance().setOnReceiveUnreadCountChangedListener(new RongIM.OnReceiveUnreadCountChangedListener() {
            @Override
            public void onMessageIncreased(int count) {
                EventBus.getDefault().post(new MessageNumEvent(count));
            }
        }, CONVERSATION_TYPES);
    }

    //下拉刷新更新HomeApps数据
    public void onEventMainThread(YspEvent.UpdateHomeApps updateHomeApps) {
        if (mMainExtraBean != null) {
            mMainExtraBean.setHomeApps(updateHomeApps.getHomeApps());
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

        }
    }

    static final class MainIntentBuilder extends BaseIntentBuilder {

        MainIntentBuilder(Context context) {
            super(context);
        }

        MainIntentBuilder setData(MainExtraBean mainExtraBean) {
            getIntent().putExtra(EXTRA_MAIN_DATA, mainExtraBean);
            return this;
        }

        MainIntentBuilder isAutoLogin(boolean autoLogin) {
            getIntent().putExtra(EXTRA_AUTO_LOGIN, autoLogin);
            return this;
        }

        @Override
        protected Class<?> getTargetClazz() {
            return MainActivity.class;
        }
    }
}
